/**
 * 广发银行借记卡抓取流程处理
 * @type {{CREDIT: string}}
 */



/**
 * 借记卡抓取主干流程
 * @param debitCardAllData
 * @param sessionInfo
 */
function debit_crawl(debitCardAllData,sessionInfo) {
    nextCard();
    /**
     * 填充表头等基础数据
     */
    cgb_debit_handle.fillBaseData(debitCardAllData);
    /**
     * 抓取借记卡信息
     */
    cgb_debit_handle.crawlCardInfo();
    /**
     *解析卡信息，填充借记卡存款信息
     */
    cgb_debit_handle.parseCardInfo(debitCardAllData);
    /**
     * 抓取借记卡账单
     */
    cgb_debit_handle.crawlDONE();
    /**
     * 解析借记卡已出账单
     */
    cgb_debit_handle.parseDONE(debitCardAllData);
}

/**
 * ######################################定义变量的位置#########################################
 */
//储蓄卡的ID
var chuxukaId = 0;



/**
 * ######################################(面向对象)封装广发借记卡的抓取处理#########################################
 */
var cgb_debit_handle= {

    /**
     * @description:填充表头等基础数据
     * @param debitCardAllData:待填充数据的借记卡对象
     * @param seesionHashMap:包含信息例子如下：
     "accountNo": "6225683322000024538",
     "accountType": "21",
     "accountName": "王新宇",
     "accountAlias": null,
     "currencyType": null,
     "openNode": "133011",
     "openNodeName": "广发银行股份有限公司大连中山支行",
     "owner": "0",
     "right": "11111010",
     "sasbDepositNo": "",
     "icon": null,
     "oldAccNo": "6225683322000024538",
     "sortNo": null,
     "accountProperty": "B",
     "cardTypeNo": "22",
     "locationNo": ""
     */
    fillBaseData:function(debitCardAllData) {
        try {
            debitCardAllData.setNameOnCard(baseMap.get(keys.USER_NAME));
            debitCardAllData.setCardType("借记卡");
            var fullAccountNo = baseMap.get(keys.USER_ACCOUNTNO);
            debitCardAllData.setFullCardNum(fullAccountNo);
            debitCardAllData.setCardNum(fullAccountNo.substring(fullAccountNo.length() - 4));
            debitCardAllData.setOpenBank(baseMap.get("openNodeName"));
        } catch (e) {
            logger.error("广发借记卡基础信息解析异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
        }
    },

    /**
     * @description:抓取借记卡信息
     * @param
     */
    crawlCardInfo:function() {

        var c = Calendar.getInstance();
        //var endDate = TimeUtil.getTimeStr(c.getTime(), "yyyyMMdd");
        c.add(Calendar.MONTH, -12);// 查询12个月的数据
        //var beginDate = TimeUtil.getTimeStr(c.getTime(), "yyyyMMdd");
        var postdata = new LinkedHashMap(32);
        postdata.put("cardNo", baseMap.get(keys.USER_ACCOUNTNO));
        postdata.put("sasbDepositNo", "");
        postdata.put("currencyType", "99");
        postdata.put("productName", "999");
        postdata.put("cardState", "A");
        postdata.put("pageQueryFlag", "FT");
        postdata.put("isAutoDump", "");
        postdata.put("turnPageBeginPos", "1");
        postdata.put("EMP_SID", baseMap.get(keys.EMP_SID));
        postdata.put("submitTimestamp", TimeUtil.getTimeStr(new Date(), "yyyyMMddHHmmssSSS"));
        postdata.put("trxCode", "b010101");
        logger.info(BankCode.CGB + "借记卡" + card + " 卡信息开始,taskkey {}", context.get(Constants.LUA_TASK_KEY));
        var cardInfoJson = ajax_post(urls.DEBIT_CARDINFO_0, postdata);
        storeDataToFile(context, cardInfoJson, card + "_card_" + (card_Id++) + ".html");
        context.put(keys.CARD_INFO, cardInfoJson);
    },

    /**
     *解析卡信息，填充借记卡存款信息
     * @param cardInfoJson
     *         卡信息页面，包含json数据
     * @param debitCardAllData
     *         待填充数据的借记卡对象
     */
     parseCardInfo:function(debitCardAllData) {
        try {
            var cardInfoHtml = context.get(keys.CARD_INFO);
            var balanceMap = JSON.parseObject(cardInfoHtml);

            if (balanceMap != null && balanceMap.get("cd") != "" && balanceMap.get("cd") != null) {
                var cd = balanceMap.get("cd");
                var list = cd.get("iSubHomeAccountList");
                if (list != null) {
                    // YSV-活期 YTM-整存整取 YNT-通知存款 ATF-丰收优利 YTD-定活智能通
                    for each(var map2
                in
                    list
                )
                    {
                        var newBusinessType = map2.get("newBusinessType") == null ? "" : (map2.get("newBusinessType") + "");
                        var currencyType = map2.get("currencyType") == null ? "" : (map2.get("currencyType") + "");
                        //活期
                        if ("YSV".equals(newBusinessType)) {
                            huoqi();
                            // 整存整取
                        } else if ("YTM".equals(newBusinessType)) {
                            zhengcunzhengqu();
                        } else if ("".equals(newBusinessType)) {
                            logger.error("借记卡未解析到有效存款类型");
                        }
                    }
                }
            }
        } catch (e) {
            logger.error("广发借记卡信息解析异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
        }

        function huoqi() {
            var balance = map2.get("balance") == null ? "" : (map2.get("balance") + "");
            if ("01".equals(currencyType)) {
                debitCardAllData.setBalance(moneyChu100(balance));
            }
            //存款实例
            var deposit = getCreditCardTimeDeposit();
            deposit.setBalance(moneyChu100(balance));
            deposit.setDepositType("活期储蓄");
            deposit.setCurrencyType("01".equals(currencyType) ? "CNY" : currencyType);
            debitCardAllData.getDeposits().add(deposit);
        }

        function zhengcunzhengqu() {
            var balance = map2.get("balance") == null ? "" : (map2.get("balance") + "");
            var openDate = map2.get("openDate") == null ? "" : (map2.get("openDate") + "");
            var interestEndDate = map2.get("interestEndDate") == null ? "" : (map2.get("interestEndDate") + "");
            var savingPeriod = map2.get("savingPeriod") == null ? "" : (map2.get("savingPeriod") + "");
            var termDepositRate = map2.get("termDepositRate") == null ? "" : (map2.get("termDepositRate") + "");
            var realyPeriod = savePeroid.get(savingPeriod);
            var money = GetJiner(termDepositRate);
            var d = money.doubleValue() / 100000000;

            //存款实例
            var deposit = getCreditCardTimeDeposit();
            deposit.setBalance(moneyChu100(balance));
            deposit.setDepositType("整存整取");
            deposit.setCurrencyType("01".equals(currencyType) ? "CNY" : currencyType);
            deposit.setDepositDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(new Date(MyDateUtil.convergeTime(openDate)), "yyyy-MM-dd")));
            deposit.setDueDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(new Date(MyDateUtil.convergeTime(interestEndDate)), "yyyy-MM-dd")));
            deposit.setInterest(GetJiner(d + ""));
            if (StringUtils.isNotBlank(realyPeriod)) {
                var periodStr = realyPeriod.split("-")[0];
                deposit.setPeriod(Integer.parseInt(periodStr));
                deposit.setPeriodUnit(realyPeriod.split("-")[1]);
            }
            if (debitCardAllData.getDeposits() == null) {
                debitCardAllData.setDeposits(new ArrayList());
            }
            debitCardAllData.getDeposits().add(deposit);
        }
    },

    /**
     * 抓取借记卡账单
     */
    crawlDONE:function(){

        var postdata = new LinkedHashMap(32);
        //构建请求参数
        buildParam(postdata);
        logger.info(BankCode.CGB + "借记卡" + card + " 已出账单信息抓取开始,taskkey {}", context.get(Constants.LUA_TASK_KEY));
        //执行请求
        var doneHtml = ajax_post(urls.DONE_INFO_0, postdata);
        storeDataToFile(context, doneHtml, card + "_bill_shopping_sheets_" + (bill_ShoppingSheet_Id++) + ".html");

        //存放抓取的账单列表
        var doneMap = new HashMap(32);
        doneMap.put("1",doneHtml);

        //解析翻页参数
        var total = parsePageParam(doneHtml, postdata);
        for (var i = 2; i <= total; i++) {
            postdata.put("pageQueryFlag", "DN");
            postdata.put("pageQueryFlag4EB", "DN");
            postdata.put("turnPageBeginPage", i);
            doneHtml = ajax_post(urls.DONE_INFO_0, postdata);
            storeDataToFile(context, doneHtml, card + "_bill_shopping_sheets_" + (bill_ShoppingSheet_Id++) + ".html");
            doneMap.put(""+i,doneHtml);
        }
        context.put(keys.DONE_MAP, doneMap);
    },

    /**
     * 解析借记卡已出账单
     */
     parseDONE:function(debitCardAllData) {
        try { //获取已出账单列表
            var debitDoneHtmlList = context.get(keys.DONE_MAP);
            //清空广发借记卡默认初始化的12个月的账单对象，详见全局搜索 createData
            // 在实际解析parseDoneHandle方法中重新创建
            debitCardAllData.getBills().clear();
            for (var i = 0; debitDoneHtmlList != null && i < debitDoneHtmlList.size(); i++) {
                parseDoneHandle(debitDoneHtmlList.get(""+(i + 1)), debitCardAllData);
            }
            return;
        } catch (e) {
            logger.error("广发借记卡已出账单解析异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
        }

        //解析借记卡已出账单的具体方法
        function parseDoneHandle(html, debitCardAllData) {
            var balanceMap = JSON.parseObject(html);
            if (balanceMap != null && balanceMap.get("cd") != null && balanceMap.get("cd") != "") {
                var cd = balanceMap.get("cd");
                var iTransferDetailList = cd.get("iTransferDetailList");
                if (iTransferDetailList != null) {
                    var list = debitCardAllData.getBills();
                    var billMap = new LinkedHashMap();

                    // 将所有账单信息添加到月份与账单的映射中
                    for each(var billAllData in list){
                        billMap.put(billAllData.getBillMonth(), billAllData);
                    }

                    for each(var map2 in iTransferDetailList){
                        var billdatail = getExpense();
                        var transDate = map2.get("transDate");// 交易时间
                        var channelType = map2.get("channelType");// 交易渠道
                        // String recordDate =
                        // map2.get("recordDate");// 记录时间
                        var transTime = map2.get("transTime");// 交易时间
                        var currencyType = map2.get("currencyType");// 货币
                        var opponencyAccount = map2.get("opponencyAccount");// 对方账号
                        var opponencyAcctName = map2.get("opponencyAcctName");// 对方姓名
                        var usableBalance = map2.get("usableBalance");// 余额
                        var transferAmt = map2.get("transferAmt");// 交易金额
                        var handAmount = map2.get("handAmount");// 描述
                        var noteMsg = map2.get("noteMsg");// 备注（转账人手填内容）
                        // 交易类型，在js中看C是+ D是- 不一定对
                        var transferType = map2.get("transferType");

                        // 交易类型，在js中看C是转入 D是转出 不一定对
                        if (transferType.equals("C")) {
                            transferAmt = "-" + transferAmt;
                        }
                        billdatail.setId(UUID.randomUUID().toString());// 账单id
                        billdatail.setAmountMoney(moneyChu100(transferAmt));
                        billdatail.setBalance(moneyChu100(usableBalance));
                        billdatail.setCardNum(debitCardAllData.getCardNum());
                        // 消费类型(WITHDRAW-取现;PAYMENTS-还款：INTEREST-预期利息:OVERDUEPAYMENT-延滞金：
                        // OVERDUEFEE-超额费:INSTALLMENT.分期：
                        // SHOPPING-消费：OTHERFEE-其他费用）
                        billdatail.setCategory(classify(handAmount, billdatail.getAmountMoney()));
                        if (currencyType != null && currencyType.equals("156")) {
                            billdatail.setCurrencyType(convertCurr("人民币"));// 货比
                        }
                        billdatail.setDescription(handAmount);
                        billdatail.setNameOnOppositeCard(opponencyAcctName);
                        // e.setOppositeBank("");
                        billdatail.setOppositeCardNo(opponencyAccount);
                        var postDate = new Date(MyDateUtil.convergeTime(transDate));
                        billdatail.setPostDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(postDate, "yyyy-MM-dd")));
                        billdatail.setRemark(noteMsg);
                        // e.setTransAddr("");
                        billdatail.setTransChannel(channelType);
                        billdatail.setOrderIndex(++chuxukaId);
                        billdatail.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(yyyy_MM_dd_PARSER.format(billdatail.getPostDate()) + " " + transTime.replaceAll("(\\d{2})(\\d{2})(\\d{2})", "$1:$2:$3")));
                        // e.setTransMethod("");
                        var bill_month = TimeUtil.getTimeStr(postDate, "yyyy-MM");
                        var billAllData = billMap.get(bill_month);
                        if (billAllData == null) {// 如果账单为空，那么新构造一个
                            billAllData = getBillAllData();
                            billAllData.setBillMonth(bill_month);
                            billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(getBillDate(bill_month)));
                            billAllData.setBillId(UUID.randomUUID().toString());
                            billAllData.setBillType("");
                            billAllData.setBankName("广发银行");
                            // 将构造的放到映射中
                            billMap.put(bill_month, billAllData);
                        }
                        // 在账单中取得详单
                        var expenseList = billAllData.getShoppingSheets();
                        if (expenseList == null) {// 如果详单为空，那么构造
                            expenseList = new ArrayList();
                            // 将构造的详单放到账单中
                            billAllData.setShoppingSheets(expenseList);
                        }
                        // 将当前记录放到详单中
                        expenseList.add(billdatail);
                    }

                    // 重新初始化所有账单列表
                    if (billMap.size() > 0) {
                        debitCardAllData.getBills().clear();
                        debitCardAllData.setBills(new ArrayList(billMap.values()));
                    }
                    }
             }
        }
     }
}


/**
 * 抓取借记卡账单-构建请求参数
 */

function buildParam(postdata) {
    var c = Calendar.getInstance();
    var endDate = TimeUtil.getTimeStr(c.getTime(), "yyyyMMdd");
    c.add(Calendar.MONTH, -12);// 查询12个月的数据
    var beginDate = TimeUtil.getTimeStr(c.getTime(), "yyyyMMdd");
    postdata.put("pageQueryFlag", "FT");
    postdata.put("accNo", baseMap.get(keys.USER_ACCOUNTNO));
    postdata.put("currency", "999");
    postdata.put("beginDate", beginDate);
    postdata.put("endDate", endDate);
    postdata.put("transferDirection", "0");
    postdata.put("turnPageShowNum", "10");
    postdata.put("mediumNo", "");
    postdata.put("newBusinessType", "YSV");
    postdata.put("sasbDepositNo", "");
    postdata.put("turnPageBeginPage", "0");
    postdata.put("turnPageTotalNum", "0");
    postdata.put("turnPageCurAccNum", "0");
    postdata.put("EMP_SID", baseMap.get(keys.EMP_SID));
}
/**
 * 抓取借记卡账单-解析翻页参数
 */
function parsePageParam(html, postdata) {
    //页面总数
    var total = 0;
    var balanceMap = JSON.parseObject(html);
    if (balanceMap != null && balanceMap.get("cd") != null && balanceMap.get("cd") != "") {
        var cd = balanceMap.get("cd");
        var turnPageTotalPage = cd.get("turnPageTotalPage");
        var turnPageTotalNum = cd.get("turnPageTotalNum");
        var turnPageCurAccNum = cd.get("turnPageCurAccNum");
        var lastRecord = cd.get("lastRecord");
        if (StringUtils.isNotBlank(turnPageTotalPage) && turnPageTotalPage.matches("\\d{1,}")) {
            total = Integer.parseInt(turnPageTotalPage);
            if (postdata != null) {
                postdata.put("lastRecord", lastRecord);
                postdata.put("turnPageTotalNum", turnPageTotalNum);
                postdata.put("turnPageCurAccNum", turnPageCurAccNum);
            }
        }
    }
    return total;
}